<?php

namespace App\Http\Controllers\api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Game;

class GameController extends Controller
{


    // 删除活动
    public function del($gameId){

        $game = Game::find($gameId);
        $res = $game->delete();
        return response()->json(["code"=>200,"msg"=>"删除成功","res"=>$res]);

    }

    // 参与活动
    public function join($gameId){

        $user = \Auth::guard("api")->user();
        $user->games()->attach($gameId);

        return response()->json(["code"=>200,"msg"=>"报名成功"]);

    }

    // 获取活动列表
    public function list(){

        //$games = Game::all();
        $games = Game::withCount(["users"])->get();

        foreach ($games as $k=>$game){
            $games[$k]["type_name"] = $game->type->name;
            $games[$k]["user_icon"] = $game->user->icon;
            $games[$k]["user_name"] = $game->user->name;
            $games[$k]["venue_name"] = $game->venue->name;
        }

        return $games;
    }

    //保存活动
    public function save(Request $request){
        //保存活动

        $user = \Auth::guard("api")->user();
        $game = new Game();
        $game->title = $request->title;
        $game->user_id = $user->id;
        $game->type_id = $request->type_id;
        $game->type_id = $request->type_id;
        $game->venue_id = $request->venue_id;
        $game->datetime = $request->datetime;
        $game->number = $request->number;

        $res = $game->save();

        return response()->json(["code"=>200,"msg"=>"活动创建成功","game"=>$res]);


    }

}
